package cn.christ.com.mobilesafe.view.widgets;


import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.christ.com.mobilesafe.R;

/**
 * @author xiaozhao 自定设置界面
 */
public class SettingItemView extends LinearLayout {

	private boolean mIsChecked;
	private ImageView mIvSettingUpdate;
	private boolean mIsVisiable;

	public SettingItemView(Context context) {
		super(context);
	}

	public SettingItemView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public SettingItemView(Context context, AttributeSet attrs) {
		super(context, attrs);
		View.inflate(context, R.layout.view_setting_item, this);
		// 先获取文本值
		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);
		String text = ta.getString(R.styleable.SettingItemView_siv_text);
		mIsChecked = ta.getBoolean(R.styleable.SettingItemView_siv_checked, false);
		mIsVisiable = ta.getBoolean(R.styleable.SettingItemView_siv_visiable, true);
		int bg = ta.getInt(R.styleable.SettingItemView_siv_bg, 0);// 背景的改变，无非这个bg的改变
		ta.recycle();
		// 找控件
		TextView tvSettingName = (TextView) findViewById(R.id.tv_setting_name);
		tvSettingName.setText(text);
		// 更新图片的状态
		mIvSettingUpdate = (ImageView) findViewById(R.id.iv_setting_update);
		setChecked();
		// 更新背景的状态
		switch (bg) {
		case 0:
			setBackgroundResource(R.drawable.first_selector);
			break;
		case 1:
			setBackgroundResource(R.drawable.middle_selector);
			break;
		case 2:
			setBackgroundResource(R.drawable.last_selector);
			break;
		default:
			break;
		}
		// 设置mIvSettingUpdate是否可见
		setVisiable();
		setClickable(true);
	}

	private void setVisiable() {
		if (mIsVisiable) {
			mIvSettingUpdate.setVisibility(View.VISIBLE);
		} else {
			mIvSettingUpdate.setVisibility(View.INVISIBLE);
		}
	}

	private void setChecked() {
		if (mIsChecked) {
			mIvSettingUpdate.setImageResource(R.drawable.on);
		} else {
			mIvSettingUpdate.setImageResource(R.drawable.off);
		}
	}

	// 开关：开的时候，点一下关，关的时候，点一下开
	public void toggle() {
		mIsChecked = !mIsChecked;
		setChecked();
	}

	public void setChecked(boolean update) {
		mIsChecked = update;
		setChecked();
	}

	public boolean isChecked() {
		return mIsChecked;
	}

}
